const { searchRecord, updateRecord, getItems } = require('../../utils/feishuAPI');
Page({
  data: {
    title: '',
    content: '',
    tags: [],
    done: '未完成',
    btnText: '修改答案',
    isEditing: false  // 是否处于编辑模式
  },

  onLoad: function(options) {
    const that = this
    tt.getStorage({
      key: options.question,
      success(res) {
        console.log(res)
        if (res.data) {
          console.log("currentCard exists");
            that.data.title = res.data.title,
            that.data.content = res.data.content,
            that.data.tags =  res.data.tags
            that.data.done = res.data.done
            console.log('qaDetail')
            console.log(that.data.title)
            console.log(that.data.content)
            console.log(that.data.tags)
            that.setData({
              title: res.data.title,
              content: res.data.content,
              tags: res.data.tags,
              done: res.data.done
            })
        } else {
          console.log("currentCard don't exist");
        }
      },
    })
  },

  toggleEdit: function() {
    const that = this
    const app = getApp()
    if (this.data.isEditing) {
      // 确认修改：保存数据
      this.setData({
        btnText: '修改答案',
        isEditing: false
      });
      const query = {
        filter: {
          "conjunction": "and",
          "conditions": [
            {
              "field_name": '问题',
              "operator": "is",
              "value": [
                that.data.title
              ]
            },
          ]
        }
      };
      searchRecord('问题管理表', query)
      .then((res) => {
        console.log(res)
        if (res != 0) {
          record_id = res.data.data.items[0].record_id
          console.log(`record_id: `, record_id)
          fields = {
            '答案': that.data.content,
            '是否完成': '已完成',
            '解答人': app.globalData.classInfo['姓名']
          }
          updateRecord('问题管理表', record_id, fields)
          .then((upres) => {
            if (upres != 0) {
              console.log(`update question success`)
            } else {
              console.log(`update question success else`)
            }
          })
        } else {
          console.log(`update question failed`)
        }
      })
    } else {
      // 进入编辑模式
      this.setData({
        btnText: '确认修改',
        isEditing: true
      });
    }
  },

  onContentInput: function(e) {
    this.setData({
      content: e.detail.value
    });
  }
});